package com.java.advance.custom.mybatis.session;

import com.java.advance.custom.mybatis.proxy.MapperProxy;
import com.java.advance.custom.mybatis.config.Configuration;
import com.java.advance.custom.mybatis.config.MapperStatement;
import com.java.advance.custom.mybatis.excutor.DefaultExcutor;
import com.java.advance.custom.mybatis.excutor.Executor;
import lombok.Data;

import java.lang.reflect.Proxy;
import java.util.List;

/**
 * Created by aivin on 2019/3/10.
 */
@Data
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    private Executor executor;

    public DefaultSqlSession() {
        super();
        executor = new DefaultExcutor(configuration);
    }

    public DefaultSqlSession(Configuration configuration) {
        super();
        this.configuration = configuration;
    }

    @Override
    public <T> T selectOne(String statement, Object parameter) {
        List<T> selectList = this.selectList(statement, parameter);
        if (selectList == null || selectList.size() == 0) {
            return null;
        }
        if (selectList.size() == 1) {
            return selectList.get(0);
        }
        throw new RuntimeException("too many results");
    }

    @Override
    public <E> List<E> selectList(String statement, Object parameter) {
        MapperStatement ms = configuration.getMapperStatements().get(statement);
        return executor.query(ms, parameter);
    }

    /**
     * 使用动态代理生成实现类
     *
     * @param type
     * @param <T>
     * @return
     */
    @Override
    public <T> T getMapper(Class<T> type) {
        MapperProxy mapperProxy = new MapperProxy(this);
        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, mapperProxy);
    }
}
